<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .box{width:100px;height:100px;background: red;position: absolute;left:0;top:0;}
  </style>
</head>
<body>
  文字
  <div class="box">hello</div>
</body>
<script>
  var box = document.querySelector(".box")
  var clientW = document.documentElement.clientWidth
  var clientH = document.documentElement.clientHeight
  var boxW = box.offsetWidth
  var boxH = box.offsetHeight


  box.onmousedown = function(eve){
    var downE = eve || window.event;
    // 阻止默认事件，防止页面上文字在拖拽过程中被选中
    if(downE.preventDefault){
      downE.preventDefault();
    }else{
      downE.returnValue = false;
    }
    // 给页面添加移动事件
    document.onmousemove = function(eve){
      var moveE = eve || window.event;
      // 计算元素位置：移动时相对于页面的坐标 - 按下时相对于元素的坐标
      var l = moveE.pageX - downE.offsetX;
      var t = moveE.pageY - downE.offsetY;
      // 边界限定
      if(l < 0) l = 0;
      if(t < 0) t = 0;
      if(l > clientW-boxW) l = clientW-boxW;
      if(t > clientH-boxH) t = clientH-boxH;
      // 设置元素位置
      box.style.left = l + "px";
      box.style.top = t + "px";
    }
    // 给页面添加鼠标抬起事件
    document.onmouseup = function(){
      // 清除移动，清除抬起
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }
</script>
</html>